import tkinter
import tkmacosx
import weathe_api as weather
from PIL import Image, ImageTk
import requests
import random
import gui_chat
from tkinter.messagebox import *
import txt_control_api as tp

def resize(w_box, h_box, pil_image):
    w, h = pil_image.size
    f1 = 1.0 * w_box / w
    f2 = 1.0 * h_box / h
    factor = min([f1, f2])
    width = int(w * factor)
    height = int(h * factor)
    return pil_image.resize((width, height), Image.ANTIALIAS)

def callback(fun, **kwds):
    print(kwds)
    return lambda event, fun=fun, kwds = kwds: fun(event, **kwds)


# 判断奇数偶数美化界面
def check_jor(count):
    count = int(count)
    if count % 2 == 0:
        return "#e3f6f5"
    else:
        return "#bae8e8"


class ToolTip(object):
    def __init__(self, widget):
        self.widget = widget
        self.tip_window = None

    def show_tip(self, tip_text):
        x, y, _cx, cy = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 25
        y = y + cy + self.widget.winfo_rooty() + 25
        self.tip_window = tw = tkinter.Toplevel(self.widget)
        tw.wm_overrideredirect(True)
        tw.wm_geometry("+%d+%d" % (x, y))
        label = tkinter.Label(tw, text=tip_text, justify=tkinter.LEFT,
                         background="#ffffe0", relief=tkinter.SOLID,
                         borderwidth=1, font=("", "20", "normal"))
        label.pack(ipadx=1)
    def hide_tip(self):
        tw = self.tip_window
        self.tip_window = None
        if tw:
            tw.destroy()


def create_ToolTip(widget, text):
    tooltip = ToolTip(widget)

    def enter(event):
        tooltip.show_tip(text)

    def leave(event):
        tooltip.hide_tip()

    widget.bind('<Enter>', enter)
    widget.bind('<Leave>', leave)


def get_name(event, name):
    global open_windows
    # 启动 初始化聊天界面，启动TCP链接
    # 聊天窗口传参数，包括我是谁 发给谁
    # 加入检测该窗口是否打开的功能，修复同一人能打开多个聊天窗口
    ls = list(tp.find_current_windows())
    if name[1][1] in ls:
        showinfo("showinfo", "该聊天窗口已经启动")
    else:
        ls.append(name[1][1])
        tp.write_current_windows(ls)
        gui_chat.create_gui(name[0], name[1])


class TopBar:
    def __init__(self, username):
        self.username_str = tkinter.StringVar()
        self.username_str.set(username)
        self.Frame = tkinter.Frame(width=300, height=100, bg='white')
        # self.Frame = tkmacosx.SFrame(width=300, height=100, bg='white')
        self.top_name = tkinter.Label(self.Frame, textvariable=self.username_str, justify='left', fg="black",font=('',30))
        print(self.username_str.get())
        self.weather_info = weather.main()
        self.add_tep = self.weather_info['city']+self.weather_info['temp']+'˚C'+self.weather_info['weather']
        self.now_date = self.weather_info['date']+self.weather_info['week']
        self.tips = self.weather_info['index'][3]['detail']
        self.at_label = tkinter.Label(self.Frame, text=self.add_tep, justify='right', fg="black",font=('',23))
        self.nd_label = tkinter.Label(self.Frame, text=self.now_date, justify='right', fg="black",font=('',16))
        self.ti_label = tkinter.Label(self.Frame, text=self.tips, justify='left', fg="black",wraplength=145)
        # 设置提示框
        self.tips = self.tips.split("，")
        self.tips[-1] = "\n" + self.tips[-1]
        create_ToolTip(self.at_label, ",".join(self.tips))
        # 图标gui设计
        self.img1 = Image.open(r'img/logo.png')
        self.img1 = resize(120, 120, self.img1)
        self.img2 = ImageTk.PhotoImage(self.img1)
        self.img_label = tkinter.Label(self.Frame, image=self.img2)

    def grid(self):
        self.img_label.grid(rowspan=4,column=0)
        self.top_name.grid(row=0, column=1)
        self.at_label.grid(row=1, column=1)
        self.nd_label.grid(row=2, column=1)
        # self.ti_label.grid(row=3, column=1)
        self.Frame.grid(row=0,column=0)
        print("tt{}".format(self.username_str.get()))


class AddButton:
    def __init__(self,username,nicheng):
        # self.Frame = tkinter.Frame(width=300, height=40, bg='white')
        self.username = username
        self.nicheng = nicheng
        self.Frame = tkmacosx.SFrame(width=300, height=40, bg='white')
        self.button_text = tkinter.StringVar()
        self.button_text.set("添加好友")
        self.add_friend = tkmacosx.Button(self.Frame, textvariable=self.button_text, bg="#E0E0E0", fg="black", width=300, height=40,command=lambda :add_friend(username,nicheng))
        self.add_friend.pack()

    def grid(self):
        self.Frame.grid(row=1, column=0)


class FriendList:
    def __init__(self, username):
        global root
        self.username = username
        # 苹果专用框架
        self.Frame = tkmacosx.SFrame(root,width=300,height=400,bg="white")
        self.ls = find_all_friends(username)
        count = 1
        for i in self.ls:
            self.name_str = i[2] + "[" + i[1] + "]"
            self.to_username = [self.name_str, i[1]]
            check_jor(count)
            self.qianming = i[3]
            self.color_str = check_jor(count)
            # 有问题
            self.Frame2 = tkinter.Frame(self.Frame,bg=self.color_str)
            self.name = tkinter.Label(self.Frame2, text=self.name_str, justify='left', fg='black', bg=self.color_str,
                                      font=("微软雅黑", 14, 'bold'), width=25)
            self.qianming = tkinter.Label(self.Frame2, text=self.qianming, justify='left', fg='black', bg=self.color_str,
                                          wraplength=230, width=25)
            # 设计鼠标双击网名或者是个性签名时，运行callback函数
            self.name.bind("<Double-Button-1>", callback(get_name, name=[self.username, self.to_username]))
            self.qianming.bind("<Double-Button-1>", callback(get_name, name=[self.username, self.to_username]))
            self.count = count
            # 图标设计
            self.rand = str(random.randint(1, 18)) + " .jpg"
            self.url = '/Users/sapple/Documents/python_webchat/client/img/noun/' + self.rand
            self.img1 = Image.open(self.url)
            self.img1 = resize(50, 50, self.img1)
            self.img2 = ImageTk.PhotoImage(self.img1)
            self.img_label = tkinter.Label(self.Frame2, image=self.img2)
            # 解决循环丢失头像的问题
            self.img_label.image = self.img2
            # self.img_label = tkinter.Label(self.Frame, text="1234")
            count = count + 1
            self.Frame2.grid(row=self.count-1, column=0)
            self.img_label.grid(row=0, column=0, rowspan=2)
            self.name.grid(row=0, column=1)
            self.qianming.grid(row=1, column=1)
            self.Frame.grid(row=self.count - 1, column=0)

    def grid(self):
        self.Frame.grid(row=2,column=0)
        return self.ls

    def get_local_all(self):
        return self.ls

def find_all_friends(username):
    ses = requests.Session()
    url = 'http://127.0.0.1:4000/get_friends_list'
    dic = {'username': username}
    res = ses.post(url, dic).text
    print(res)
    return eval(res)

# 添加好友
def add_one_friend(username, nicheng,friend_name):
    all = find_all_friends(username)
    for i in all:
        if i[1] == friend_name:
            print("进入本地校验")
            print(i[1])
            showinfo("showinfo","该好友已经存在")
            return 0
    add = requests.Session()
    url = "http://127.0.0.1:4000/add_friend"
    dic = {'username': username, 'nicheng':nicheng,'friend_name':friend_name}
    print(dic)
    res = add.post(url, dic).text
    showinfo("title",res)
    return res


def add_friend(username, nicheng):
    add_tk = tkinter.Tk()
    add_tk.title("请输入对方账号")
    add_tk.geometry("300x100")
    find_username = tkinter.Entry(add_tk, bg="white", fg="black")
    # username = tkinter.Entry(add_tk,bg="white", fg="black", text="")
    button = tkmacosx.Button(add_tk, text="添加", bg="#339933", fg="black", width=100, height=40,command=lambda :add_one_friend(username,nicheng,find_username.get()))
    find_username.grid(row=0, column=0)
    button.grid(row=0, column=1)
    add_tk.mainloop()


def create_gui_list(username):
    global add_friend
    global root
    global friend_list
    global open_windows
    global loginer_info
    open_windows = []
    open_windows.append("我是窗口管理器")
    print("create{}".format(username))
    root = tkinter.Tk()
    root.geometry("290x570")
    root.title("WeTalk")
    # 顶部栏代码
    tt = TopBar(username)
    tt.grid()
    # 下方好友列表代码
    friend_list = FriendList(username)
    ls = friend_list.grid()
    # 改登陆者昵称代码
    # 好友列表放置返回值 包括昵称
    nicheng = ls[0][0]
    tt.username_str.set(nicheng)
    # 中间添加好友代码
    add = AddButton(username,nicheng)
    add.grid()

    # 运行窗口
    root.mainloop()


if __name__ == '__main__':
    create_gui_list("15133854715")

